package com.example.demo.Task;


import com.example.demo.domain.dto.Classroom;
import com.example.demo.domain.send.DingMessage;
import com.example.demo.service.CourseService;
import com.example.demo.service.SendDingMessageService;
import com.example.demo.utils.ParseUtil;
import java.util.Arrays;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 定时任务获取老师课程信息
 * @author lizijian
 */
@Slf4j
@Component
public class GetTeacherCourseTask extends TimerTask {

    private static final ThreadPoolTaskExecutor GET_TEACHER_COURSE_POOL = new ThreadPoolTaskExecutor();

    @Autowired
    private CourseService courseService;

    static {
        GET_TEACHER_COURSE_POOL.setRejectedExecutionHandler(new CallerRunsPolicy());
        GET_TEACHER_COURSE_POOL.setCorePoolSize(10);
        GET_TEACHER_COURSE_POOL.setMaxPoolSize(10);
        GET_TEACHER_COURSE_POOL.setQueueCapacity(Integer.MAX_VALUE);
        GET_TEACHER_COURSE_POOL.setWaitForTasksToCompleteOnShutdown(true);
        GET_TEACHER_COURSE_POOL.initialize();
    }

    @Override
    public void run() {
        try {
            log.info("开始爬取所有地点课表老师课程信息");
            SendDingMessageService.sendGetDataMessage(new DingMessage("开始爬取所有地点课表老师课程信息"));
            List<Classroom> allClassRoom = ParseUtil.getAllClassRoom();
            log.info("教室总数:"+allClassRoom.size());
            courseService.deleteTeacherCourse();
            for (Classroom classRoom : allClassRoom) {
                GetTeacherCourseThread getTeacherCourseThread = new GetTeacherCourseThread(
                    courseService, classRoom.getClassroomName());
                GET_TEACHER_COURSE_POOL.execute(getTeacherCourseThread);
            }
        }catch (Exception e){
            log.error("get teacher course error");
            log.error("errorMessage:"+e.getMessage());
            log.error("stack:"+ Arrays.toString(e.getStackTrace()));
            SendDingMessageService.sendGetDataMessage(new DingMessage("爬取所有地点课表老师课程信息失败：errorMessage："+e.getMessage()));
        }
    }
}
